import { _decorator, Component, UITransform, EventTouch, v3, Node } from 'cc';
import { TipsObjectType, ITipsObject } from '../../../Game/Config/GameEnum';
import { FlyTipsPanel } from './FlyTipsPanel';

const { ccclass, property } = _decorator;

@ccclass('TipsManager')
export class TipsManager extends Component {
  static Singleton: TipsManager;

  @property(FlyTipsPanel)
  flyTipsPanel: FlyTipsPanel = null!;

  private freeArea: UITransform;
  /** 可以触发点击的tip有且只有一个 */
  private curTip: Node;
  private tipsType: TipsObjectType;

  constructor() {
    super();
    TipsManager.Singleton = this;
  }

  setTipClick() {
    this.node.on(Node.EventType.TOUCH_START, this.onClickPanel, this);
    this.node.on(Node.EventType.TOUCH_MOVE, this.onCanel, this);
    this.node.on(Node.EventType.TOUCH_CANCEL, this.onCanel, this);
    this.node.on(Node.EventType.TOUCH_END, this.onCanel, this);
  }

  removeTipClick() {
    this.node.off(Node.EventType.TOUCH_START, this.onClickPanel, this);
    this.node.off(Node.EventType.TOUCH_MOVE, this.onCanel, this);
    this.node.off(Node.EventType.TOUCH_CANCEL, this.onCanel, this);
    this.node.off(Node.EventType.TOUCH_END, this.onCanel, this);
    this.freeArea = null;
    this.tipsType = null;
  }

  onClickPanel(event: EventTouch) {
    event.preventSwallow = true;
    if (this.freeArea != null && this.curTip != null) {
      const clickPos = event.getUILocation();
      const pos = this.freeArea.convertToNodeSpaceAR(v3(clickPos.x, clickPos.y));
      const xx = -this.freeArea.width * this.freeArea.anchorX;
      const yy = -this.freeArea.height * this.freeArea.anchorY;
      if (pos.x > xx && pos.x < xx + this.freeArea.width && pos.y > yy && pos.y < yy + this.freeArea.height) {
        // console.log('click free');
        return;
      }
    }
    this.canelTip();
  }

  private onCanel(event: EventTouch) {
    event.preventSwallow = true;
  }

  canelTip() {
    switch (this.tipsType) {
      case TipsObjectType.miniWinTips:
        this.curTip.active = false;
        this.curTip = null;
        this.removeTipClick();
        break;
      default:
        this.removeTipClick();
        break;
    }
  }

  showTips(data: ITipsObject) {
    switch (data.type) {
      case TipsObjectType.flyTips:
      case TipsObjectType.flyText:
        this.flyTipsPanel.flyTips(data);
        break;
      case TipsObjectType.miniWinTips:
        this.tipsType = TipsObjectType.miniWinTips;
        this.shopDropDown(data);
        break;
    }
  }

  shopDropDown(data: ITipsObject) {
    const targetNode = data.data['node'];
    if (this.curTip != null) {
      if (this.curTip != targetNode) {
        this.curTip.active = false;
      }
    } else {
      this.setTipClick();
    }
    this.curTip = targetNode;
    this.freeArea = data.data['form'];
    this.curTip.active = true;
  }
}
